//package com.jg.elearning.gateway.filter.pre;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
//import UserSessionBean;
//import Base64;
//import com.sie.iot.common.bean.SIEJWTResult;
//import com.sie.iot.common.util.SIEJWTUtils;
//import com.sie.iot.userbehavior.model.entities.BaseBehaviorEntity_HI;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.cloud.gateway.filter.GatewayFilterChain;
//import org.springframework.cloud.gateway.filter.GlobalFilter;
//import org.springframework.core.Ordered;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.data.redis.core.ValueOperations;
//import org.springframework.data.redis.serializer.RedisSerializer;
//import org.springframework.data.redis.serializer.StringRedisSerializer;
//import org.springframework.http.server.reactive.ServerHttpRequest;
//import org.springframework.kafka.core.KafkaTemplate;
//import org.springframework.stereotype.Component;
//import org.springframework.web.server.ServerWebExchange;
//import reactor.core.publisher.Mono;
//import java.io.BufferedReader;
//import java.io.IOException;
//import java.io.InputStreamReader;
//import java.net.InetAddress;
//import java.net.NetworkInterface;
//import java.util.List;
//@Component
//public class AccessFilter implements GlobalFilter, Ordered {
//    @Autowired
//    private RedisTemplate redisTemplate;
//    @Autowired
//    private KafkaTemplate kafkaTemplate;
//
//
//    private BaseBehaviorEntity_HI packagingBaseBehaviorEntityHi(ServerHttpRequest request) {
//        String tokenAuthorization =  request.getHeaders().getFirst("authorization");
//
//        SIEJWTResult siejwtResult = SIEJWTUtils.validateJWT(tokenAuthorization);
//        JSONObject subjectJSON = JSONObject.parseObject(siejwtResult.getClaims().getSubject());
//        String loginForm = subjectJSON.getString("loginFrom");
//        String phoneNumber = subjectJSON.getString("phoneNumber");
//        String username = subjectJSON.getString("username");
//
//        String systemCode = request.getHeaders().getFirst("systemCode");
//        systemCode = systemCode!=null? Base64.decode(systemCode):null;
//
//        String requestMenuUrl = request.getHeaders().getFirst("requestMenuUrl");
//        requestMenuUrl = requestMenuUrl!=null? Base64.decode(requestMenuUrl):null;
//
//        String controllerURL = request.getHeaders().getFirst("controllerURL");
//        controllerURL = controllerURL!=null? Base64.decode(controllerURL):null;
//
//        String pageName = request.getHeaders().getFirst("pageName");
//        pageName = pageName!=null? Base64.decode(pageName):null;
//
//        String buttonName = request.getHeaders().getFirst("buttonName");
//        buttonName = buttonName!=null? Base64.decode(buttonName):null;
//
//        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
//        redisTemplate.setKeySerializer(stringSerializer);
//        redisTemplate.setValueSerializer(stringSerializer);
//        ValueOperations valueOperations = redisTemplate.opsForValue();
//        String sessionKey = "session:" + username + phoneNumber + loginForm;
//        String result = valueOperations.get(sessionKey) != null ? String.valueOf(valueOperations.get(sessionKey)) : "";
//        UserSessionBean userSessionBean = JSON.toJavaObject(JSON.parseObject(result), UserSessionBean.class);
//        BaseBehaviorEntity_HI baseBehaviorEntityHi = new BaseBehaviorEntity_HI();
//        try {
//            String ipAddress = getIpAddr(request);
//            baseBehaviorEntityHi.setClientIp(ipAddress);
//            //String macAddress = getMACAddress(ipAddress);
//           // baseBehaviorEntityHi.setMacAddress(macAddress);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        baseBehaviorEntityHi.setPhoneNumber(phoneNumber);
//        baseBehaviorEntityHi.setUserName(username);
//        baseBehaviorEntityHi.setUserId(userSessionBean.getUserId());
//        baseBehaviorEntityHi.setOperatorUserId(userSessionBean.getUserId());
//
//        baseBehaviorEntityHi.setSystemCode(systemCode);
//        baseBehaviorEntityHi.setControllerUrl(controllerURL);
//        baseBehaviorEntityHi.setPageName(pageName);
//        baseBehaviorEntityHi.setButtonName(buttonName);
//        baseBehaviorEntityHi.setDeviceType(loginForm);
//        baseBehaviorEntityHi.setExceptionCode(null);
//        baseBehaviorEntityHi.setExceptionDetail(null);
//        //截取 最大256
//        if (requestMenuUrl!=null&&requestMenuUrl.length()>250){
//            baseBehaviorEntityHi.setPageUrl(requestMenuUrl.substring(0,250));
//        }else{
//            baseBehaviorEntityHi.setPageUrl(requestMenuUrl);
//        }
//        return baseBehaviorEntityHi;
//    }
//
//    /**
//     * 通过HttpServletRequest返回IP地址
//     * @param request HttpServletRequest
//     * @return ip String
//     * @throws Exception
//     */
//    public String getIpAddr(ServerHttpRequest request) throws Exception {
//        String ip = request.getHeaders().getFirst("x-forwarded-for");
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeaders().getFirst("Proxy-Client-IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeaders().getFirst("WL-Proxy-Client-IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeaders().getFirst("HTTP_CLIENT_IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeaders().getFirst("HTTP_X_FORWARDED_FOR");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getRemoteAddress().getHostString();
//        }
//        return ip;
//    }
//    /**
//     * 通过IP地址获取MAC地址
//     * @param ip String,127.0.0.1格式
//     * @return mac String
//     * @throws Exception
//     */
//    public String getMACAddress(String ip) throws Exception {
//        String line = "";
//        String macAddress = "";
//        final String MAC_ADDRESS_PREFIX = "MAC Address = ";
//        final String LOOPBACK_ADDRESS = "127.0.0.1";
//        //如果为127.0.0.1,则获取本地MAC地址。
//        if (LOOPBACK_ADDRESS.equals(ip)) {
//            InetAddress inetAddress = InetAddress.getLocalHost();
//            //貌似此方法需要JDK1.6。
//            byte[] mac = NetworkInterface.getByInetAddress(inetAddress).getHardwareAddress();
//            //下面代码是把mac地址拼装成String
//            StringBuilder sb = new StringBuilder();
//            for (int i = 0; i < mac.length; i++) {
//                if (i != 0) {
//                    sb.append("-");
//                }
//                //mac[i] & 0xFF 是为了把byte转化为正整数
//                String s = Integer.toHexString(mac[i] & 0xFF);
//                sb.append(s.length() == 1 ? 0 + s : s);
//            }
//            //把字符串所有小写字母改为大写成为正规的mac地址并返回
//            macAddress = sb.toString().trim().toUpperCase();
//            return macAddress;
//        }
//        //获取非本地IP的MAC地址
//        try {
//            Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
//            InputStreamReader isr = new InputStreamReader(p.getInputStream());
//            BufferedReader br = new BufferedReader(isr);
//            int i = 0;
//            while ((line = br.readLine()) != null) {
//                System.out.println(i++);
//
//                System.out.println("line===="+line);
//
//                long start = System.currentTimeMillis();
//                if (line != null) {
//                    int index = line.indexOf(MAC_ADDRESS_PREFIX);
//                    if (index != -1) {
//                        macAddress = line.substring(index + MAC_ADDRESS_PREFIX.length()).trim().toUpperCase();
//                    }
//                }
//                long end = System.currentTimeMillis();
//
//                System.out.println(end-start);
//            }
//            br.close();
//        } catch (IOException e) {
//            e.printStackTrace(System.out);
//        }
//        return macAddress;
//    }
//
//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        BaseBehaviorEntity_HI baseBehaviorEntityHi = null;
//        try {
//            baseBehaviorEntityHi = packagingBaseBehaviorEntityHi(exchange.getRequest());
//        }catch (Throwable e){
//            //所有的错误暂时全部不处理
//        }
//        if(null != baseBehaviorEntityHi){
//            kafkaTemplate.send("message_base_behavior",JSONObject.toJSONString(baseBehaviorEntityHi));
//        }
//        return chain.filter(exchange);
//    }
//
//    @Override
//    public int getOrder() {
//        return 20;
//    }
//
//    private boolean containUri(List<String> listStr, String requestURI) {
//        for (String str : listStr) {
//            if (str.indexOf("*") > 0) {
//                str = str.replaceAll("\\*", "");
//                if (requestURI.startsWith(str)) {
//                    return true;
//                }
//            } else {
//                if (str.equals(requestURI)) {
//                    return true;
//                }
//            }
//        }
//        return false;
//    }
//}
